package org.jeecg.modules.factor.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.api.DTO.EmissionFactorUnitDTO;
import org.jeecg.modules.api.VO.EmissionFactorQueryUnitVO;
import org.jeecg.modules.api.VO.EmissionFactorUnitVO;
import org.jeecg.modules.api.entity.CyEmissionUnit;
import org.jeecg.modules.factor.request.SynchronousUnitRequest;
import org.jeecg.modules.factor.service.ICyEmissionUnitConvertService;
import org.jeecg.modules.factor.service.ICyEmissionUnitService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description: 碳排因子单位
 * @Author: jeecg-boot
 * @Date:   2024-11-01
 * @Version: V1.0
 */
@Api(tags="碳排因子单位")
@RestController
@RequestMapping("/emission/factor/cyEmissionUnit")
@Slf4j
public class CyEmissionUnitController extends JeecgController<CyEmissionUnit, ICyEmissionUnitService> {
	@Autowired
	private ICyEmissionUnitService cyEmissionUnitService;

	 @Autowired
	 private ICyEmissionUnitConvertService cyEmissionUnitConvertService;    //碳排因子单位换算Service层

	/**
	 * 分页列表查询
	 *
	 * @param cyEmissionUnit 碳排因子单位对象
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "碳排因子单位-分页列表查询")
	@ApiOperation(value="碳排因子单位-分页列表查询", notes="碳排因子单位-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CyEmissionUnit cyEmissionUnit,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		IPage<EmissionFactorQueryUnitVO> emissionFactorQueryUnitVOIPage = cyEmissionUnitService.queryPageList(cyEmissionUnit, pageNo, pageSize);
		return Result.OK(emissionFactorQueryUnitVOIPage);
	}


	/**
	 * 查询所有单位(用于新增碳排因子时，选择因子分母单位的接口)
	 *
	 * @return allUnit 所有因子分母单位集合
	 */
	@ApiOperation(value="碳排因子单位-查询所有单位", notes="碳排因子单位-查询所有单位")
	@GetMapping(value = "/getAllUnit")
	public Result<?> getAllUnit() {
		List<CyEmissionUnit> allUnit = cyEmissionUnitService.getAllUnit();
		return Result.ok(allUnit);
	}

	/**
	 * 查询所有单位并且分组
	 *
	 * @return allUnitGroup 所有因子分母单位并分组的集合
	 */
	@ApiOperation(value="碳排因子单位-查询所有单位并且分组", notes="碳排因子单位-查询所有单位并且分组")
	@GetMapping(value = "/getAllUnitByGroup")
	public Result<?> getAllUnitByGroup() {
		Map<String, List<CyEmissionUnit>> allUnitByGroup = cyEmissionUnitService.getAllUnitByGroup();
		return Result.ok(allUnitByGroup);
	}


	/**
	 *   添加
	 *
	 * @param emissionFactorUnitDTO 碳排因子新增对象
	 * @return
	 */
	@AutoLog(value = "碳排因子单位-添加")
	@ApiOperation(value="碳排因子单位-添加", notes="碳排因子单位-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:cy_emission_unit:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody EmissionFactorUnitDTO emissionFactorUnitDTO) {

		Result<String> Result = cyEmissionUnitService.addUnit(emissionFactorUnitDTO);
		return Result;
	}

	 /**
	  *   通过id删除
	  *
	  * @param id 碳排因子单位id
	  * @return
	  */
	 @AutoLog(value = "碳排因子单位-通过id删除")
	 @ApiOperation(value="碳排因子单位-通过id删除", notes="碳排因子单位-通过id删除")
	 //@RequiresPermissions("org.jeecg.modules.demo:cy_emission_unit:delete")
	 @DeleteMapping(value = "/delete")
	 public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		 cyEmissionUnitService.deleteById(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  * 详情
	  *
	  * @param id 碳排因子单位id
	  * @return
	  */
	 @ApiOperation(value="碳排因子单位-详情", notes="碳排因子单位-详情")
	 @GetMapping(value = "/queryById")
	 public Result<EmissionFactorUnitVO> queryById(@RequestParam(name="id",required=true) String id) {
		 EmissionFactorUnitVO emissionFactorUnitVO = cyEmissionUnitService.queryById(id);
		 if(emissionFactorUnitVO ==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(emissionFactorUnitVO);
	 }

	/**
	 *  编辑
	 *
	 * @param emissionFactorUnitDTO
	 * @return
	 */
	@AutoLog(value = "碳排因子单位-编辑")
	@ApiOperation(value="碳排因子单位-编辑", notes="碳排因子单位-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:cy_emission_unit:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody EmissionFactorUnitDTO emissionFactorUnitDTO) {
		cyEmissionUnitService.editUnit(emissionFactorUnitDTO);
		return Result.OK("编辑成功!");
	}


	/**
	 * 导出excel
	 *
	 * @param request
	 * @param cyEmissionUnit
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, CyEmissionUnit cyEmissionUnit) {
		return super.exportXls(request, cyEmissionUnit, CyEmissionUnit.class, "碳排因子单位表");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//		return super.importExcel(request, response, CyEmissionUnit.class);

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				long start = System.currentTimeMillis();
				List<CyEmissionUnit> list = ExcelImportUtil.importExcel(file.getInputStream(), CyEmissionUnit.class, params);
				if (list == null || list.size() == 0){
					return Result.error("文件获取出的数据为空！");
				}
				Result<String> backMessage = cyEmissionUnitService.importEmissionUnit(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return backMessage;
			} catch (Exception e) {
				//update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
				String msg = e.getMessage();
				log.error(msg, e);
				if(msg!=null && msg.indexOf("Duplicate entry")>=0){
					return Result.error("文件导入失败:有重复数据！");
				}else{
					return Result.error("文件导入失败:" + e.getMessage());
				}
				//update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/**
	 * 根据对应关系同步因子单位
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/synchronousEmissionFactorUnit", method = RequestMethod.POST)
	public Result<?> synchronousEmissionFactorUnit(HttpServletRequest request, HttpServletResponse response) {

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				long start = System.currentTimeMillis();
				List<SynchronousUnitRequest> list = ExcelImportUtil.importExcel(file.getInputStream(), SynchronousUnitRequest.class, params);
				if (list == null || list.size() == 0){
					return Result.error("文件获取出的数据为空！");
				}
				Result<String> backMessage = cyEmissionUnitService.synchronousEmissionFactorUnit(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return backMessage;
			} catch (Exception e) {
				//update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
				String msg = e.getMessage();
				log.error(msg, e);
				if(msg!=null && msg.indexOf("Duplicate entry")>=0){
					return Result.error("文件导入失败:有重复数据！");
				}else{
					return Result.error("文件导入失败:" + e.getMessage());
				}
				//update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}







}
